<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
      <div>
          <n-form ref="form"
                  :model="searchCondition"
                  label-placement="left"
                  label-align="right"
                  label-width="80px"
                  :show-require-mark="false">
          <div>
              <div class="grid md:flex md:flex-wrap md:gap-x-1">
                <n-form-item>
                  <label>创建人：</label>
                  <n-select
                      placeholder="创建人" :options="admins" v-model:value="searchCondition.adminId">
                  </n-select>
                </n-form-item>
                <n-form-item style="margin-left: 5px;">
                  <n-button type="primary"  @click="searchByCondition">筛选</n-button>
                </n-form-item>
                <n-form-item style="margin-left: 12px">
                  <n-button type="primary" @click="showForm = true">
                    添加属性
                  </n-button>
                </n-form-item>
                <n-form-item style="--n-width: 70px; margin-left: 15px;padding: 0">
                  <n-button type="error" @click="deleteSelectAttribute">
                    批量删除
                  </n-button>
                </n-form-item>
                <n-form-item style="margin-left: 10px">
                  <n-button type="primary" @click="exportListInfo">导出</n-button>
                </n-form-item>
              </div>
            </div>
          <AddAttributeForm
              :option="option"
              @update-page="searchByCondition"
              :show="showForm"
              :onClose="handleClose"
              :attribute="currentAttribute"
          />
          <UpdateAttributeForm
              :option="option"
              @update-page="searchByCondition"
              :show1="showForm1"
              :onClose="handleClose"
              :attribute="currentAttribute"
           />
          <n-data-table
              remote
              :single-line="false"
              ref="table"
              :columns="columns"
              :data="attributeList"
              :loading="loading"
              :pagination="paginationReactive"
              :row-key="rowKey"
              :scroll-x="900"
              @update:checked-row-keys="handleCheck"
          />
        </n-form>
      </div>
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import { onMounted, reactive, ref, h } from 'vue'
import api from '@/api/admin';
import { useUserStore } from '@/store';
import { useRouter } from 'vue-router';
import AddAttributeForm from './components/attribute-add.vue';
import CategoryActions from "@/views/admin/category/components/category-actions.vue";
import UpdateAttributeForm from './components/attribute-edit.vue'

const attributeList = ref([])
const option = ref([])
const showForm = ref(false);
const showForm1 = ref(false);
const currentAttribute = ref(null); // 当前编辑的属性

const handleClose = () => {
  showForm.value = false;
  showForm1.value = false;
};

const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const range = ref(null)
const value = ref("全部")
const checkedRowKeysRef = ref([]);
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const admins = ref([])
admins.value.push({
  label: '全部',
  value: -1,
})
const searchCondition = ref({
  adminId: -1,
});
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
  {
    key: 'id',
    title: '属性编号',
    width: 70,
  },
  {
    key: 'categoryName',
    title: '分类名称',
    width: 100,
    render(row) {
      if (row["categoryId"] === null) {
        return "无"
      }
      return row["categoryName"]
    }
  },
  {
    key: 'specification',
    title: '产品规格',
    width: 100,
  },
  {
    key: 'color',
    title: '产品颜色',
    width: 100,
  },
  {
    key: 'material',
    title: '产品材质',
    width: 100,
  },
  {
    key: 'adminName',
    title: '创建人',
    width: 100,
  },
  {
    key: 'createTime',
    title: '创建时间',
    width: 100,

  },
  {
    key: 'operation',
    title: '操作',
    width: 100,
    render(row) {
      return h(
          CategoryActions,
          {
            onClickDelete: () => onDeleteProductAttribute(row),
            onClickEdit: () => onEditProductAttribute(row),
          }
      );
    }
  },
]
let total = 0
const paginationReactive = reactive({
  page: 1,
  pageSize: 20,
  showSizePicker: true,
  pageSizes: [20, 50, 100],
  itemCount: 0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});
const deleteSelectAttribute = () => {
  if (checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择属性！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选属性？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      loading.value = true
      try {
        const res = await api.deleteProductAttributes({ params: { ids } })
        if (res.code === 200) {
          $message.success("删除所选属性成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选属性失败！")
      } finally {
        loading.value = false
      }
    },
  })
}
const searchByCondition = async () => {
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageProductAttribute({
      params: {
        adminId: searchCondition.value.adminId.toString(),
        pageNum: paginationReactive.page,
        pageSize: paginationReactive.pageSize,
      }
    })
    if (res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1) * paginationReactive.pageSize
      attributeList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: baseCount + i + 1,
        }
      })
      $message.success("获取产品属性成功！")
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询产品属性失败！")
  } finally {
    loading.value = false
  }
}
const exportListInfo = async () => {
  const res = await api.exportProductAttributeList({
    adminId: searchCondition.value.adminId.toString(),
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if (contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else {
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.style.display = 'none'
    const href = window.URL.createObjectURL(blob)
    elink.href = href
    elink.download = fileName
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const onDeleteProductAttribute = (row) => {
  $dialog.warning({
    title: '警告',
    content: '您确定删除此产品属性？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      loading.value = true
      try {
        const res = await api.deleteProductAttribute({ params: { id: row.id } })
        if (res.code === 200) {
          $message.success("删除产品属性成功！")
          await queryByPage()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除产品属性失败！")
      } finally {
        loading.value = false
      }
    }
  })
}
const onEditProductAttribute = async (productAttribute) => {
  currentAttribute.value = productAttribute; // 设置当前编辑的属性
  showForm1.value = true; // 显示编辑窗口
}
const queryByPage = async () => {
  loading.value = true
  try {
    const res = await api.findPageProductAttribute(
        {
          params: {
            pageNum: paginationReactive.page,
            pageSize: paginationReactive.pageSize,
          }
        })
    if (res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      attributeList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: i + 1
        }
      })
      $message.success("获取产品全部属性成功！")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取产品属性失败！")
  }finally{
    loading.value = false
  }
}
const queryAllProductCategory = async  () => {
  try {
    const res = await api.findAllProductCategory()
    if(res.code === 200) {
      // 调用函数生成n-cascader的options
      convertToCascaderOptions(res.data);
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取属性失败！")
  }finally{
    loading.value = false
  }
}
const queryAdminList = async () => {
  loading.value = true
  try {
    const res = await api.findAdminsInProductAttribute()
    if(res.code === 200) {
      res.data.map((item)=>{
        admins.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取管理员信息失败！")
  }finally{
    loading.value = false
  }
}
const convertToCascaderOptions = (flatData) => {
  const idNodeMap = {}; // 用于映射id到对应的节点对象
  const opt = []; // 最终生成的级联选择器数据
  // 首先，将所有的数据节点放到一个映射表中，方便后续通过ID快速查找
  flatData.forEach(node => {
    idNodeMap[node.id] = { ...node, children: [] };
  });
  // 构建树形结构
  Object.values(idNodeMap).forEach(node => {
    if (node.parentCategoryId === null) {
      // 如果parentId为null，则该节点是根节点
      opt.push(node);
    } else {
      // 否则，将该节点添加到其父节点的children数组中
      const parentNode = idNodeMap[node.parentCategoryId];
      if (parentNode) {
        parentNode.children.push(node);
      }
    }
  });
  // 遍历并转换所有根节点
  option.value = opt.map(node=>{
    return traverse(node)
  });
}
// 转换数据结构为n-cascader所接受的格式（将name转换为label，并移除不必要的字段）
const traverse = (node) => {
  const { id, name, children } = node;
  // 如果children数组为空，则不返回children字段
  const processedNode = {
    value: id.toString(),
    label: name,
    ...(children.length > 0 ? { children: children.map(child => traverse(child)) } : {})
  };
  return processedNode;
};
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(()=>{
  queryAdminList()
  queryAllProductCategory()
  queryByPage()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
  text-align: center;

}
:deep(.n-select) {
  width: 140px !important;
}

:deep(.two-line-description) {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 控制显示的行数 */
  overflow: hidden;
}

</style>
